<?php

namespace app\data\controller\base;

use app\data\model\DataSwiper;
use app\data\model\DataNewsItem;
use app\data\model\ShopGoods;
use app\data\model\ShopGoodsBrand;
use think\admin\Controller;
use think\admin\model\SystemBase;

/**
 * 图片内容管理
 * Class Slider
 * @package app\data\controller\base
 */
class Slider extends Controller
{
    /**
     * 跳转规则定义
     * @var string[]
     */
    protected $rules = [
        '#'  => ['name' => '不跳转'],
        'LK' => ['name' => '自定义链接'],
        'NL' => ['name' => '新闻资讯列表'],
        'NS' => ['name' => '新闻资讯详情', 'node' => 'data/news.item/select'],
    ];

    /**
     * 数据类型
     * @var string
     */
    protected $type = '图片内容';

    /**
     * 页面类型
     * @var array
     */
    protected $types = [];

    /**
     * 控制器初始化
     * @return void
     */
    protected function initialize()
    {
        $this->types = SystemBase::mk()->items($this->type);
        foreach ($this->types as &$type) {
            if (preg_match('/^(.*?)#(\d+)$/', $type['name'], $matches)) {
                $type['name'] = $matches[1];
                $type['number'] = $matches[2];
            } else {
                $type['number'] = 0;
            }
        }
    }

    /**
     * 图片内容管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '图片内容管理';
        $this->fetch();
    }

    /**
     * 编辑图片内容
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->skey = input('get.type', '');
        $this->base = $this->types[$this->skey] ?? [];
        if (empty($this->base)) $this->error('未配置基础数据！');
        $this->number = $this->base['number'];
        $this->sysdata();
    }

    /**
     * 保存图片内容
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function sysdata()
    {
        if ($this->request->isGet()) {
            $this->title = "{$this->base['name']}管理";
            //获取品牌列表
            $brand = ShopGoodsBrand::mk()->where(['status'=>1])->column('id,name,remark');
            //获取文章列表
            $news = DataNewsItem::mk()->where(['status'=>1,'deleted'=>0])->column('id,name,mark');
            //获取商品列表
            $goods = ShopGoods::mk()->where(['status'=>1])->column('id,name');
            $this->brands = $brand;
            $this->news = $news;
            $this->goods = $goods;
            //轮播
            $swiperList = DataSwiper::mk()->where(['status'=>1])->order(array('sort'=>'asc'))->field("cover as img,id,brand_id,new_id,good_id,type")->select();
            $this->data = $swiperList;
            $this->fetch('form');
        } else {
            $data = input('data','');
            if(empty($data)) return \Tools::returnMsg(false,array(
                'code'  => '10004',
                'message'=>'参数错误'
            ));
            $data = json_decode($data,true);
            $res = 0;
            //删除轮播
            $opera= [];
            DataSwiper::mk()->startTrans();
            $ids = [];
            foreach($data as $k=>$dv){
                $info = array(
                    'cover' => $dv['img'],
                    'type'  => $dv['type'],
                    'create_at' => \Tools::getDateTimeByTime(),
                    'sort'  => $k
                );
                if($dv['type'] == 1){
                    $info['brand_id'] = $dv['brand_id'];
                    $info['new_id'] = 0;
                    $info['good_id'] = 0;
                }elseif($dv['type'] == 2){
                    $info['brand_id'] = 0;
                    $info['new_id'] = $dv['new_id'];
                    $info['good_id'] = 0;
                }else{
                    $info['brand_id'] = 0;
                    $info['new_id'] = 0;
                    $info['good_id'] = $dv['good_id'];
                }
                if(isset($dv['id']) && $dv['id'] > 0){
                    $opera[] = DataSwiper::mk()->where(array(
                        'id'    => $dv['id']
                    ))->update($info);
                    $ids[] = $dv['id'];
                }else{
                    $opera[] = DataSwiper::mk()->insert($info);
                    $ids[] = DataSwiper::mk()->getLastInsID();
                }
            }
            $has = DataSwiper::mk()->whereNotIn('id',$ids)->select()->toArray();
            if(empty($has) === FALSE) {
                $opera[] = DataSwiper::mk()->whereNotIn('id', $ids)->delete();
            }
            if(\Tools::checkArrayResult($opera)){
                DataSwiper::mk()->commit();
                $this->success("{$this->base['name']}保存成功！");
            }else{
                DataSwiper::mk()->rollBack();
                $this->error("{$this->base['name']}保存失败，请稍候再试!");
            }
        }
    }
}
